﻿$(function () {
    var l = abp.localization.getResource('BookStore');
    var createModal = new abp.ModalManager(abp.appPath + 'Books/CreateModal');
    var editModal = new abp.ModalManager(abp.appPath + 'Books/EditModal');

    var inputAction = function () {
        return { name: ($('#NameQueryInput').val() || ""), authorName: ($('#AuthorNameQueryInput').val() || "") };
    };

    var dataTable = $('#BooksTable').DataTable(
        abp.libs.datatables.normalizeConfiguration({
            serverSide: true,
            paging: true,
            order: [[1, "asc"]],
            searching: false,
            scrollX: true,
            ajax: abp.libs.datatables.createAjax(acme.bookStore.books.book.getList, inputAction),
            columnDefs: [
                {
                    title: l('Actions'),
                    rowAction: {
                        items:
                            [
                                {
                                    text: l('Edit'),
                                    visible: abp.auth.isGranted('BookStore.Books.Edit'), //CHECK for the PERMISSION
                                    action: function (data) {
                                        editModal.open({ id: data.record.id });
                                    }
                                },
                                {
                                    text: l('Delete'),
                                    visible: abp.auth.isGranted('BookStore.Books.Delete'),
                                    confirmMessage: function (data)
                                    {
                                        return l("BookDeletionConfirmationMessage", data.record.name);
                                    },
                                    action: function (data) {
                                        acme.bookStore.books.book
                                            .delete(data.record.id)
                                            .then(function () {
                                                abp.notify.info(l('SuccessfullyDeleted'));
                                                dataTable.ajax.reload();
                                            });
                                    }
                                }
                            ]
                    }
                },
                {
                    title: l('Name'),
                    data: "name"
                },
                {
                    title: l('Author'),
                    data: "authorName"
                },
                {
                    title: l('Type'),
                    data: "type",
                    render: function (data) {
                        return l('Enum:BookType:' + data);
                    }
                },
                {
                    title: l('PublishDate'),
                    data: "publishDate",
                    render: function (data) {
                        return luxon
                            .DateTime
                            .fromISO(data, {
                                locale: abp.localization.currentCulture.name
                            }).toLocaleString();
                    }
                },
                {
                    title: l('Price'),
                    data: "price"
                },
                {
                    title: l('CreationTime'), data: "creationTime",
                    render: function (data) {
                        return luxon
                            .DateTime
                            .fromISO(data, {
                                locale: abp.localization.currentCulture.name
                            }).toLocaleString(luxon.DateTime.DATETIME_SHORT);
                    }
                }
            ]
        })
    );

    createModal.onResult(function () {
        dataTable.ajax.reload();
    });

    editModal.onResult(function () {
        dataTable.ajax.reload();
    });

    $("#SearchButton").click(function () {
        dataTable.ajax.reload();
    });

    $('#NewBookButton').click(function (e) {
        e.preventDefault();
        createModal.open();
    });

    $("#ImportTemplateButton").click(function (e) {
        //console.log("下载");
        //const req = new XMLHttpRequest();
        //req.open('POST', '/api/app/book/import-template', true);
        //req.responseType = 'blob'; //如果不指定，下载后文件会打不开
        //req.setRequestHeader('Content-Type', 'application/json');
        //req.onload = function (e2) {
        //    console.log("onload触发", e2);
        //    console.log("onload");
        //    var content = req.getResponseHeader("Content-Disposition");
        //    //console.log("onload触发", content, req.response);
        //    //// 文件名最好用后端返的Content-disposition
        //    //// 需要后端设置 Access-Control-Expose-Headers: Content-disposition 使得浏览器将该字段暴露给前端
        //    //var name = content && content.split(';')[1].split('filename=')[1];
        //    //var fileName = decodeURIComponent(name)
        //    //downloadFile(fileName, req.response)
        //};
        //req.send();

        $.ajax({
            type: "POST",
            url: "/api/app/book/import-template",
            xhrFields: { responseType: "blob" },
            success: (response) => {
                console.log("resp", response);
                const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                const blobUrl = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = blobUrl;
                a.download = '书籍列表导入模板.xlsx';
                a.target = '_blank';
                a.click();
            }
        })


        //abp.ajax({
        //    url: "/api/app/book/import-template",
        //    type: "POST",
        //    responseType: 'blob',
        //    xhrFields: { responseType: "blob" },
        //}).then(data => {
        //    console.log("data", data);
        //}).catch(e => {
        //    console.log("err", e);
        //})


        //abp.ajax($.extend(true, {
        //    url: "/api/app/book/import-template",
        //    type: 'Post',
        //    xhrFields: { responseType: "blob" },
        //})).then(data =>
        //{
        //    console.log("data", data);
        //}).catch(e =>
        //{
        //    console.log("err", e);
        //})

        //$.ajax({
        //    type: "POST",
        //    url: "/api/app/book/import-template",
        //    xhrFields: { responseType: "blob" },
        //    success: (response) => {
        //        console.log("resp", response);
        //        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        //        const blobUrl = URL.createObjectURL(blob);
        //        const a = document.createElement('a');
        //        a.style.display = 'none';
        //        a.href = blobUrl;
        //        a.target = '_blank';
        //        a.click();
        //    }
        //})

        //abp.ajax($.extend(true, {
        //    url: '/api/app/book/import-template',//控制器方法地址
        //    type: 'Post'
        //}
        //    //, app.createInquireinputFilter("AdvacedAuditFiltersArea", "InRecordLogsTableFilter")
        //)).done(function (data) {
        //    console.log("data", data);
        //    //app.downloadTempFile(data);//根據返回的對象信息下載文件，主要是文件名

        //});
    });

    $("#ImportBookButton").click(function (e)
    {
        let el = document.getElementById("uploadInput");
        if (el) {
            el.parentElement.removeChild(el);
        }
        let input = document.createElement("input");
        input.accept = "";
        input.multiple = false;
        input.id = "uploadInput";
        input.type = "file";
        input.style.display = "none";
        document.body.appendChild(input);

        return new Promise((resolve, reject) => {
            input.onchange = async function (e) {
                await Promise.all([
                    ...Array.from(e.target.files).map(file => {
                        console.log("file", file);

                        return new Promise((res1) => {
                            res1({ fileBlob: file, fileName: file.name });
                        })
                    })
                ])
                    .then((resp) => {
                        let formData = new FormData();
                        formData.append("file", resp[0].fileBlob);
                        return $.ajax({
                            type: 'post',
                            url: '/api/app/book/import',
                            data: formData,
                            processData: false,
                            contentType: false,
                            dataType: 'json',
                            success: function (res) {
                                abp.notify.success(`成功导入${res}行数据`, "导入成功", { positionClass: "toast-top-center"});
                                resolve(resp);
                            },
                            error: function (err) {
                                abp.notify.error(err, "导入失败", { positionClass: "toast-top-center" });
                                reject(err);
                            }
                        });
                    })
            };
            input.click();
        })
        .then(() => {
            dataTable.ajax.reload();
        });
    })

    $("#ExportBookButton").click(function (e) {
        $.ajax({
            type: "POST",
            url: `/api/app/book/Export?Name=${($('#NameQueryInput').val() || "")}&AuthorName=${($('#AuthorNameQueryInput').val() || "") }`,
            xhrFields: { responseType: "blob" },
            success: (response) => {
                console.log("resp", response);
                const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                const blobUrl = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = blobUrl;
                a.download = '书籍列表.xlsx';
                a.target = '_blank';
                a.click();
            }
        })
    });
    function downloadFile(fileName, blob) {
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob);
        link.style.display = 'none';
        link.download = fileName;
        document.body.appendChild(link)
        link.click();
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link)
    };
});